<template>
	<view class="login-form">
		<up-form labelWidth="60px" labelPosition="left" :model="formData" :rules="rules" ref="formRef">
			<up-form-item required label="手机号" prop="phone" borderBottom>
				<up-input v-model="formData.phone" placeholder="请输入手机号">
					<template #suffix>
						<up-code ref="uCodeRef" @change="codeChange" seconds="5" changeText="X秒重新获取哈哈哈"></up-code>
						<up-button @tap="getCode" :text="tips" type="success" size="mini"></up-button>
					</template>
				</up-input>
			</up-form-item>
			<up-form-item required prop="code" label="验证码" borderBottom>
				<up-input placeholder="请输入内容" border="surround" v-model="formData.code"></up-input>
			</up-form-item>
		</up-form>
		<up-button @click="submit">登录</up-button>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		GET_CODE,
		DO_LOGIN
	} from '@/api/login';

	const formData = ref({
		phone: '',
		code: ''
	})
	const formRef = ref(null)
	const uCodeRef = ref(null)
	const codeChange = (text) => {
		console.log(text)
		tips.value = text;
	};
	const rules = ref({
		phone: {
			type: 'string',
			required: true,
			message:'请输入手机号',
			trigger: ['blur', 'change']
		},
		code: {
			type: 'string',
			required: true,
			message:'请输入验证码',
			trigger: ['blur', 'change']
		}
	})
	const tips = ref('');
	const getCode = () => {
		console.log(formData.value.phone)
		if(!formData.value.phone) {
			uni.$u.toast('请输入手机号');
			return
		}
		if (uCodeRef.value.canGetCode) {
			// 模拟向后端请求验证码
			uni.showLoading({
				title: '正在获取验证码',
			});
			GET_CODE().then(res => {
				console.log(res)
				uni.hideLoading();
				// 这里此提示会被start()方法中的提示覆盖
				uni.$u.toast('验证码已发送');
				// 通知验证码组件内部开始倒计时
				uCodeRef.value.start();
				uni.setStorageSync('code', res.data.code)
			})
			// setTimeout(() => {
			//   uni.hideLoading();
			//   // 这里此提示会被start()方法中的提示覆盖
			//   uni.$u.toast('验证码已发送');
			//   // 通知验证码组件内部开始倒计时
			//   uCodeRef.start();
			// }, 2000);
		} else {
			uni.$u.toast('倒计时结束后再发送');
		}
	}
	
	const submit = () => {
		formRef.value.validate().then(valid => {
			console.log(valid)
			// 校验通过
			if(valid) {
				const localCode = uni.getStorageSync('code')
				if(localCode === formData.value.code) {
					//本地存的code就是接口返回的code，如果与输入的验证码一致
					// 就去登录
					DO_LOGIN(formData.value.phone).then(res => {
						console.log(res)
						if(res.data.msg==='ok') {
							uni.setStorageSync('phone', res.data.phone)
							uni.setStorageSync('token', res.data.token.token)
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
				} else {
					uni.$u.toast('验证码输入错误');
				}
			}
		})
	}
</script>

<style lang="scss">
	.login-form{
		width: 80vw;
		margin: 0 auto;
	}
</style>